<template>
  <div class="app-container">
    <el-row>
      <div style="margin: 4px 0 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">{{ template.name }}</span>
      </div>
    </el-row>
    <el-card class="box-card">
      <div v-if="chooseHeader !== null">
        <div v-if="chooseHeader.json==null">
          <tenkvHeader ref="Header" :header-form-origin="headerFormOrigin"/>
        </div>
        <div v-else-if="chooseHeader.hasOwnProperty('json')">
          <v-form-render ref="Header" :form-data="headerFormOrigin" :form-json="getClearFormJson(chooseHeader.json)"/>
        </div>
      </div>
      <el-row>
        <el-col style="text-align: center;" :offset="19" :span="5">
          <el-button icon="el-icon-folder-checked" type="primary" :disabled="isReadOnly" @click.native="saveHeader()">
            保存修改内容
          </el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">表单项</span>
      </div>
    </el-row>
    <el-card ref="mainBody" v-loading="listLoading" style="position: relative" :element-loading-text="loadingText"
             :element-loading-background="loadingColor"
    >
      <div v-for="(item,index) in bodyRenderList" :key="index" style="margin: 24px 0;">
        <custom-question-block v-if="item.json==null"
                               v-model="bodyModelValue[`${item.oid}`]"
                               :question-block="item" :order="false"
        />
        <v-form-render v-else :form-json="getClearFormJson(item.json)"
                       :form-data="bodyModelValue[`${item.oid}`].retData"
                       :ref="`${item.oid}`" v-model="bodyModelValue[`${item.oid}`]"
        />
        <el-row style="margin-top: 12px;display: flex;align-items: center;">
          <el-col :span="5" class="check-block">自检：
            <sign v-if="refresh" :time="checkTime[`${item.oid}_Scheck`]" :img="signModelValue[`${item.oid}`].scheck"
                  :item="item.oid" @click.native="saveInfo(item.oid)" @submit="subs($event,item.oid)"
                  @delete="deleteS"
            />
          </el-col>
          <el-col v-if="JSON.stringify(item.json).indexOf('Ocheck')!==-1" :span="5" class="check-block">互检：
            <sign v-if="refresh" :time="checkTime[`${item.oid}_Ocheck`]" :img="signModelValue[`${item.oid}`].ocheck"
                  :item="item.oid" @click.native="saveInfo(item.oid)" @submit="subo($event,item.oid)"
                  @delete="deleteO"
            />
          </el-col>
          <el-col v-if="JSON.stringify(item.json).indexOf('Zcheck')!==-1" :span="5" class="check-block">Z检：
            <sign v-if="refresh" :time="checkTime[`${item.oid}_Zcheck`]" :img="signModelValue[`${item.oid}`].zcheck"
                  :item="item.oid" @click.native="saveInfo(item.oid)" @submit="subz($event,item.oid)"
                  @delete="deleteZ"
            />
          </el-col>
          <el-col :span="4" style="text-align:center;height: 100%;z-index: 501;">
            <el-button style="z-index: 501;" icon="el-icon-edit"
                       :type="problemValue[item.oid]|problemFilter(record[item.oid])"
                       @click="openProblemDialog(item.oid)"
            >问题记录
            </el-button>
          </el-col>
          <el-col :span="5" style="text-align: center;height: 100%;">
            <el-button icon="el-icon-folder-checked" type="primary" :disabled="isReadOnly"
                       @click="saveItemContent(item.oid)"
            >保存修改内容
            </el-button>
          </el-col>
        </el-row>
        <el-table
          v-loading="listLoading"
          :data="fileData.filter(i => item.oid == i.realname.split('.')[0].split('_')[0])"
          style="width: 50%;margin-top: 12px;"
          border
        >
          <el-table-column
            width="82"
            label="id"
            prop="fid"
          />
          <el-table-column
            label="文件名"
            prop="realname"
          />

          <el-table-column align="center" width="242">
            <template slot="header" slot-scope="scope">
              <div style="width: 100%;text-align: center;">
                <el-button :disabled="isReadOnly" size="small" type="primary" @click="upFile(item.oid)">添加文件
                </el-button>
                <input :ref="`singleFile${item.oid}`" type="file" style="display: none;"
                       @change="handleFileUpload($event,item.oid)"
                >
              </div>

            </template>
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="handleDownload(scope.row.realname,scope.row.path)"
              >查看
              </el-button>
              <el-button
                size="mini"
                type="danger"
                :disabled="isReadOnly"
                @click="handleDelete(scope.row.fid)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-divider/>
      </div>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">表尾信息</span>
      </div>
    </el-row>
    <el-card>
      <div v-if="chooseTail !== null">
        <div v-if="chooseTail.json==null">
          <tenkvTail ref="Tail" :tail-form="tailForm" :is-read-only="isReadOnly"/>
        </div>
        <div v-else-if="chooseTail.hasOwnProperty('json')">
          <v-form-render ref="Tail" :form-data="tailForm" :form-json="getClearFormJson(chooseTail.json)"/>
        </div>
      </div>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">附件上传</span>
      </div>
    </el-row>
    <el-card v-loading="fileLoading" :element-loading-text="loadingText" :element-loading-background="loadingColor">
      <el-table
        v-loading="listLoading"
        :data="fileData"
        style="width: 100%"
        border
      >
        <el-table-column
          width="82"
          label="id"
          prop="fid"
        />
        <el-table-column
          label="文件名"
          prop="realname"
        />

        <el-table-column align="center" width="242">
          <template slot="header" slot-scope="scope">
            <div style="width: 100%;text-align: center;">
              <el-button slot="trigger" :disabled="isReadOnly" size="small" type="primary" @click="upFile('')">添加文件
              </el-button>
              <input ref="singleFile" type="file" style="display: none;" @change="handleFileUpload($event)">
            </div>

          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleDownload(scope.row.realname,scope.row.path)"
            >下载
            </el-button>
            <el-button
              size="mini"
              type="danger"
              :disabled="isReadOnly"
              @click="handleDelete(scope.row.fid)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-row>
      <div style="margin: 20px 0px 20px 4px;">
        <span style="font-size: 20px; font-weight: bold">返厂信息</span>
      </div>
    </el-row>
    <el-card v-if="isPublish">
      <el-form ref="returnForm" :model="returnForm" label-width="80px">
        <el-form-item label="返厂原因">
          <el-input v-model="returnForm.reason" :rows="2" autosize type="textarea"/>
        </el-form-item>
        <el-form-item label="返厂处理">
          <el-input v-model="returnForm.process" :rows="2" autosize type="textarea"/>
        </el-form-item>
        <el-form-item>
          <el-row>
            <el-col style="text-align: center;" :offset="19" :span="5">
              <el-button icon="el-icon-folder-checked" type="primary" @click="saveReturn">保存修改内容</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-card>
    <el-row style="margin: 24px 0px 24px 0px;">
      <el-form :inline="true" style="display: flex; justify-content: center;">
        <el-button v-if="!isReadOnly" type="primary" @click="submitDialogFormVisible = true">流转</el-button>
        <el-button v-if="!isReadOnly" type="primary" @click="saveAllContentBtn">保存全部</el-button>
        <el-button v-if="!isReadOnly" type="success" @click="archiveBtn">归档</el-button>
        <el-button @click="$router.push({path:'/workOrderSys/myCreation'})">返回</el-button>
      </el-form>
    </el-row>
    <el-dialog top="4vh" :close-on-click-modal="false" width="80%" title="问题记录" :visible.sync="problemDialog">
      <el-form ref="rproblemForm" :disabled="isReadOnly" label-position="left" :model="problemFrom" status-icon
               label-width="96px" style="margin-left: 12px"
      >
        <el-form-item label="问题:">
          <el-checkbox-group v-model="problemFrom.list">
            <el-checkbox label="1" name="type">卡滞</el-checkbox>
            <el-checkbox label="2" name="type">分合</el-checkbox>
            <el-checkbox label="3" name="type">采购品</el-checkbox>
            <el-checkbox label="4" name="type">后事故</el-checkbox>
            <el-checkbox label="5" name="type">掉漆</el-checkbox>
            <el-checkbox label="6" name="type">特性</el-checkbox>
            <el-checkbox label="7" name="type">其他</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="问题描述:">
          <el-input v-model="problemFrom.commit" type="textarea"/>
        </el-form-item>
        <el-form-item label="问题签名:" class="space-item" @click.prevent="t">
          <sign :time="problemFrom.signTime" :img="problemFrom.sign" @delete="deleteProblem" @submit="saveProblemSign"/>
          <div style="flex-grow: 1;"/>
          <el-button :disabled="isReadOnly" type="primary" @click="subProblem">提 交</el-button>
        </el-form-item>
        <el-divider/>
        <el-form-item label="问题处理:">
          <el-input v-model="problemFrom.record" type="textarea"/>
        </el-form-item>
        <el-form-item label="记录签名:" class="space-item" @click.prevent="t">
          <sign :time="problemFrom.handlerTime" :img="problemFrom.handlerSign" @delete="deleteRecord"
                @submit="saveRecordSign"
          />
          <div style="flex-grow: 1;"/>
          <el-button :disabled="isReadOnly" type="primary" @click="subRecord">提 交</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="problemDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="流转工单" :visible.sync="submitDialogFormVisible">
      <el-form ref="ruleForm" :model="queryUser" status-icon class="demo-ruleForm" style="margin-left: 12px">
        <el-form-item>
          <span>该操作将流转工单，请确认。</span>
        </el-form-item>
        <el-form-item label="工单流转至:">
          <el-input v-model="queryUser.keyword" placeholder="请输入姓名或工号" style="width: 200px;"
                    prefix-icon="el-icon-search"
                    size="small"
                    @keyup.enter.native="searchUser(1)"
          />
          <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 12px" @click="searchUser(1)">
            搜索
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="listLoading"
        :data="searchList"
        style="width: 100%"
      >
        <el-table-column
          label="工号"
          prop="uid"
        />
        <el-table-column
          label="姓名"
          prop="username"
        />
        <el-table-column
          align="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleTo(scope.row.uid)"
            >流转给TA
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
        <el-pagination
          :page-size="5"
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          :total="total"
          @current-change="searchUser(currentPage)"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="subToFreeStore">流转至自由状态</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CustomRadio from '@/components/CustomRadio'
import tenkvHeader from '@/components/fixedForm/tenkvHeader.vue'
import {
  archiveOrder,
  deleteFile, deleteProblem, deleteProblemSign, deleteRecord, deleteRecordSign, fillTableItem,
  getFile,
  getOrderByTid, getRecord, getTemplateBody, getTemplateHeader, getTemplateTail,
  modifyDraft, oCheck, postProblem, postRecord, saveReturn,
  sCheck, toFreeStore,
  uploadOrderFile,
  zCheck
} from '@/api/table'
import {getClearFormJson, MAPPER, PAGE_SIZES} from '@/utils/common'
import CustomQuestionBlock from '@/components/CustomQuestionBlock'
import {spheader, handleHeader, sptail, reverseHeader} from '@/utils/fix/pre'
import {deleteUser, findUser} from '@/api/user'
import {BASE_URL} from '@/utils/request'
import Sign from '@/components/Sign'
import {moveOrder} from '../../api/table'
import {deleteCheck, getCheckTime, modifyOrder} from '@/api/order'
import TenkvTail from '@/components/fixedForm/tenkvTail.vue'
import fa from 'element-ui/src/locale/lang/fa'

const allComponents = require.context('@/components/CustomQuestionBlock/questions', false, /\.vue$/)
const res_components = {}
allComponents.keys().forEach(fileName => {
  const comp = allComponents(fileName)
  res_components[fileName.replace(/^\.\/(.*)\.\w+$/, '$1')] = comp.default
})
export default {
  components: {TenkvTail, tenkvHeader, Sign, CustomRadio, ...res_components, CustomQuestionBlock},
  name: 'OrderDetail',
  filters: {
    problemFilter(item, record) {
      console.log(record)
      if (item) {
        if (item.list.length === 0 && item.otherValue === '' && item.commit === '') {
          return ''
        } else {
          if (record === null || record.sign === null || record.sign === 'need' || record.sign === '') {
            return 'warning'
          } else {
            return 'success'
          }
        }
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      returnForm: {
        reason: '',
        process: ''
      },
      that: this,
      checkTime: {},
      loadingText: '加载中',
      isReadOnly: false,
      loadingColor: 'hsla(0,0%,100%,.5)',
      problemFrom: {
        record: '',
        item: -1,
        sign: '',
        list: [],
        commit: '',
        otherValue: '',
        signFile: null,
        handlerSign: '',
        handlerSignFile: null,
        signTime: null,
        handlerTime: null
      },
      problemDialog: false,
      refresh: true,
      toSubInfo: null,
      fileLoading: false,
      searchList: [],
      currentPage: 1,
      pageSize: PAGE_SIZES,
      total: 0,
      MAPPER: MAPPER,
      headerFrom: {...spheader},
      tailForm: {...sptail},
      queryUser: {
        keyword: '',
        status: '',
        dateRange: []
      },
      list: [],
      listLoading: true,
      fileList: [],
      headerFormOrigin: {},
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      orgNum: '',
      id: '',
      saveDialogFormVisible: false,
      submitDialogFormVisible: false,
      template: {body_list: []},
      bodyModelValue: {},
      signModelValue: {},
      problemValue: {},
      fileData: [],
      record: {},
      isPublish: false,
      bodyRenderList: [],
      bodyTemplates: [],
      headerTemplates: [],
      tailTemplates: [],
      chooseHeader: null,
      chooseTail: null
    }
  },
  async created() {
    try {
      const [bodyResponse, headerResponse, tailResponse] = await Promise.all([
        getTemplateBody(),
        getTemplateHeader(),
        getTemplateTail()
      ])
      this.bodyTemplates = bodyResponse.data.data
      this.headerTemplates = headerResponse.data.data
      this.tailTemplates = tailResponse.data.data
    } catch (error) {
      console.error('发生错误：', error)
    }
    const tid = this.$route.query.tid
    if (tid) {
      this.getRecord(tid)
      this.getCheckTime(tid)
      getOrderByTid(tid).then(res => {
        const {data} = res
        this.template = data
        if (data.type === 2) {
          this.isPublish = true
          this.returnForm.reason = data.return_reason
          this.returnForm.process = data.return_process
        }
        // if (data.handler_info.uid !== this.$store.getters.userInfo.uid || data.type !== 1) {
        //   this.isReadOnly = true
        //   this.$message.warning('该表单处于只读状态')
        //   this.$loading({
        //     target: this.$refs.mainBody.$el,
        //     spinner: '  ',
        //     background: 'rgba(255,255,255,0)',
        //     customClass: 'fl'
        //   })
        // }
        this.chooseHeader = this.headerTemplates.find((item) => {
          return item.oid === this.template.header_id
        })
        this.chooseTail = this.tailTemplates.find((item) => {
          return item.oid === this.template.tail_id
        })

        if (this.chooseHeader.json == null) {
          this.headerFormOrigin = {...reverseHeader(this.template.header_value)}
        } else {
          this.headerFormOrigin = JSON.parse(this.template.header_value).retData
        }

        if (this.chooseTail.json == null) {
          this.tailForm = JSON.parse(this.template.tail_value)
        } else {
          this.tailForm = JSON.parse(this.template.tail_value).retData
          this.$nextTick(() => {
            this.$refs.Tail.disableForm()
          })
        }

        for (const item of data.body_data) {
          this.bodyModelValue[item.oid] = JSON.parse(item.content)
          if (this.bodyModelValue[item.oid].retData != null) {
            this.bodyModelValue[item.oid].retData = JSON.parse(this.bodyModelValue[item.oid].retData)
          }
          const data = {
            scheck: item.scheck === 'need' ? '' : item.scheck,
            ocheck: item.ocheck === 'need' ? '' : item.ocheck,
            zcheck: item.zcheck === 'need' ? '' : item.zcheck
          }
          this.signModelValue[item.oid] = data
          this.problemValue[item.oid] = JSON.parse(item.problem)
        }

        for (const item of data.body_list) {
          const find = this.bodyTemplates.find(i => i.oid === item)
          this.bodyRenderList.push(find)
        }

        getFile(this.template.tid).then(res => {
          this.fileData = res.data
          this.listLoading = false
        })
      })
    } else {
      this.$router.go(-1)
    }
  },
  mounted() {

  },
  methods: {
    getClearFormJson,
    getBodyValue() {
      for (let item of this.bodyRenderList) {
        if (item.json != null) {
          this.bodyModelValue[`${item.oid}`] = this.$refs[`${item.oid}`][0].getFormData(false)
        }
      }
    },
    getRecord(tid) {
      return new Promise((resolve, rej) => {
        getRecord(tid).then(res => {
          res.data.forEach((item) => {
            this.record[item.oid] = item
          })
          resolve(res)
        })
      })
    },
    getCheckTime(tid) {
      getCheckTime(tid).then(res => {
        res.data.forEach(item => {
          this.checkTime[`${item.oid}_${item.type}`] = (new Date(item.created_at)).Format('yyyy-MM-dd hh:mm')
        })
        this.reload()
      })
    },
    saveReturn() {
      const form = new FormData()
      form.append('reason', this.returnForm.reason)
      form.append('process', this.returnForm.process)
      saveReturn(this.template.tid, form).then(res => {
        this.$message.success('保存成功')
      })
    },
    saveHeader() {
      const header = this.$refs.Header.getFormData(false)
      modifyOrder(this.template.tid, {content: header}).then(res => {
        this.$message.success('保存表头信息成功')
      })
    },
    saveAllContentBtn() {
      this.saveAllContent().then(res => {
        this.$router.go(-1)
      })
    },
    confirmArchive(tid) {
      this.$confirm('此操作将结束该工单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        archiveOrder(tid).then(res => {
          this.$message({
            type: 'success',
            message: '结单成功!'
          })
          this.$router.go(-1)
        })
      })
    },
    archiveBtn() {
      this.saveAllContent().then(res => {
        this.confirmArchive(this.template.tid)
      })
    },
    saveAllContent() {
      this.getBodyValue()
      const temp = []
      for (const item in this.bodyModelValue) {
        this.bodyModelValue[item].num = this.template.body_list.indexOf(item) + 1
        temp.push({oid: item, data: this.bodyModelValue[item]})
      }
      const x = temp.map((item) => {
        return fillTableItem(this.template.tid, item.oid, {content: item.data})
      })
      const header = this.$refs.Header.getFormData(false)
      x.push(modifyOrder(this.template.tid, {content: header}).then(res => {
        this.$message.success('保存表头信息成功')
        return res
      }))
      return new Promise((res, rej) => {
        Promise.all(x).then(values => {
          let flag = true
          console.log(values)
          for (const i of values) {
            if (i.msg !== '成功') {
              flag = false
              break
            }
          }
          if (flag) {
            this.$message.success('保存成功！')
            res('保存成功')
          } else {
            this.$message.error('保存失败，请重新保存')
            rej('保存失败')
          }
        })
      })
    },
    subToFreeStore() {
      this.saveAllContent().then(values => {
        toFreeStore(this.template.tid).then(res => {
          this.$message.success('流转成功')
          this.$router.go(-1)
        })
      })
    },
    saveProblemSign(s, base) {
      if (s !== 1) {
        this.problemFrom.signFile = s
        this.problemFrom.sign = base
      } else {
        this.problemFrom.sign = this.$store.getters.userInfo.sign_img
        this.problemFrom.signFile = null
      }
    },
    saveRecordSign(s, base) {
      if (s !== 1) {
        this.problemFrom.handlerSignFile = s
        this.problemFrom.handlerSign = base
      } else {
        this.problemFrom.handlerSign = this.$store.getters.userInfo.sign_img
        this.problemFrom.handlerSignFile = null
      }
    },
    openProblemDialog(item) {
      this.problemFrom.item = item
      this.problemFrom.signFile = null
      this.problemFrom.sign = ''
      this.problemFrom.commit = ''
      this.problemFrom.list = []
      this.problemFrom.signTime = null
      this.problemFrom.handlerTime = null
      this.problemFrom.handlerSign = ''
      this.problemFrom.record = ''
      if (this.problemValue[item]) {
        this.problemFrom.sign = this.problemValue[item].sign
        this.problemFrom.commit = this.problemValue[item].commit
        this.problemFrom.list = this.problemValue[item].list
        if (this.record[item]) {
          if (this.record[item].sign === 'need') {
            this.record[item].sign = ''
          }
          this.problemFrom.handlerSign = this.record[item].sign
          this.problemFrom.record = this.record[item].record
          if (this.record[item].created_at && this.problemFrom.sign) {
            this.problemFrom.signTime = (new Date(this.record[item].created_at)).Format('yyyy-MM-dd hh:mm')
          } else {
            this.problemFrom.signTime = null
          }
          if (this.record[item].updated_at) {
            this.problemFrom.handlerTime = (new Date(this.record[item].updated_at)).Format('yyyy-MM-dd hh:mm')
          } else {
            this.problemFrom.handlerTime = null
          }
        }
      }
      if (this.problemFrom.record === 'null') {
        this.problemFrom.record = ''
      }
      this.problemDialog = true
    },
    reload() {
      this.refresh = false
      this.$nextTick(() => {
        this.refresh = true
      })
    },
    saveItemContent(oid) {
      this.getBodyValue()
      let content = this.bodyModelValue[`${oid}`]
      content.num = this.template.body_list.indexOf(oid) + 1
      fillTableItem(this.template.tid, oid, {content: content}).then(res => {
        this.$message.success('保存成功')
      }).catch(() => {
        this.$message.success('保存失败，请重新保存')
      })
    },
    deleteRecord() {
      this.$confirm(`此操作将清除问题处理签名, 是否继续?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRecordSign(this.template.tid, this.problemFrom.item).then(res => {
          this.record[this.problemFrom.item].sign = null
          this.record[this.problemFrom.item].updated_at = null
          this.openProblemDialog(this.problemFrom.item)
          this.$message.success('撤回成功')
        })
      }).catch(() => {
      })
    },
    subRecord() {
      if (!this.problemValue[this.problemFrom.item]) {
        this.$message.error('还未添加问题，无法填写问题处理')
        return
      }
      const recordFormData = new FormData()
      recordFormData.append('record', this.problemFrom.record)
      if (this.problemFrom.handlerSignFile) {
        recordFormData.append('file', this.problemFrom.handlerSignFile)
      }
      postRecord(this.template.tid, this.problemFrom.item, recordFormData).then(res => {
        this.getRecord(this.template.tid).then(res1 => {
          this.openProblemDialog(this.problemFrom.item)
        })
        this.$message.success('修改问题记录成功')
      })
    },
    subProblem() {
      const data = {
        commit: this.problemFrom.commit,
        list: this.problemFrom.list,
        otherValue: ''
      }
      const formData = new FormData()
      formData.append('problem', JSON.stringify(data))
      if (this.problemFrom.signFile) {
        formData.append('file', this.problemFrom.signFile)
      }
      postProblem(this.template.tid, this.problemFrom.item, formData).then(res => {
        this.problemValue[res.data.oid] = JSON.parse(res.data.problem)
        this.getRecord(this.template.tid).then(res1 => {
          this.openProblemDialog(res.data.oid)
        })
        this.$message.success('修改问题成功')
      })
    },
    deleteProblem() {
      this.$confirm(`此操作将清除问题签名, 是否继续?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProblemSign(this.template.tid, this.problemFrom.item).then(res => {
          this.problemValue[this.problemFrom.item].sign = null
          this.problemValue[this.problemFrom.item].created_at = null
          // delete this.record[this.problemFrom.item]
          this.openProblemDialog(this.problemFrom.item)
          this.$message.success('撤回成功')
        })
      }).catch(() => {
      })
    },
    saveInfo(i) {
      console.log('出发了save')
      this.getBodyValue()
      this.toSubInfo = i
    },
    deleteS(oid) {
      this.$confirm(`此操作将撤回签名, 是否继续?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCheck(this.template.tid, oid, 'Scheck').then(res => {
          this.$message.success('撤回成功')
          this.signModelValue[oid].scheck = ''
          delete this.checkTime[`${oid}_Scheck`]
          this.reload()
        })
      }).catch(() => {
      })
    },
    async subs(s, id) {
      this.toSubInfo = id
      const content = this.bodyModelValue[`${this.toSubInfo}`]
      const oid = this.toSubInfo
      content.num = this.template.body_list.indexOf(oid) + 1
      if (this.toSubInfo == 1 || this.toSubInfo == 2) {
        content.fe = ''
      }
      let x = content.fe
      if (x === undefined) x = '未填写完整'
      fillTableItem(this.template.tid, oid, {content: content}).then(res => {
        if (x === '') {
        } else {
          this.$message.error(x)
          return
        }
        if (s === 1) {
          sCheck(this.template.tid, this.toSubInfo).then(res => {
            this.signModelValue[res.data.oid].scheck = res.data.scheck
            this.getCheckTime(this.template.tid)
            this.reload()
            this.$message.success('签字成功')
          })
        } else {
          const formData = new FormData()
          formData.append('file', s)
          sCheck(this.template.tid, this.toSubInfo, formData).then(res => {
            this.signModelValue[res.data.oid].scheck = res.data.scheck
            this.getCheckTime(this.template.tid)
            this.reload()
            this.$message.success('签字成功')
          })
        }
      }).catch(() => {
        this.$message.error('签字失败，请重新签字')
      })
    },
    deleteO(oid) {
      this.$confirm(`此操作将撤回签名, 是否继续?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCheck(this.template.tid, oid, 'Ocheck').then(res => {
          this.$message.success('撤回成功')
          this.signModelValue[oid].ocheck = ''
          delete this.checkTime[`${oid}_Ocheck`]
          this.reload()
        })
      }).catch(() => {
      })
    },
    subo(s, id) {
      this.toSubInfo = id
      if (s === 1) {
        oCheck(this.template.tid, this.toSubInfo).then(res => {
          this.signModelValue[res.data.oid].ocheck = res.data.ocheck
          this.getCheckTime(this.template.tid)
          this.reload()
          this.$message.success('签字成功')
        })
      } else {
        const formData = new FormData()
        formData.append('file', s)
        oCheck(this.template.tid, this.toSubInfo, formData).then(res => {
          this.signModelValue[res.data.oid].ocheck = res.data.ocheck
          this.getCheckTime(this.template.tid)
          this.reload()
          this.$message.success('签字成功')
        })
      }
    },
    deleteZ(oid) {
      this.$confirm(`此操作将撤回签名, 是否继续?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCheck(this.template.tid, oid, 'Zcheck').then(res => {
          this.$message.success('撤回成功')
          this.signModelValue[oid].zcheck = ''
          delete this.checkTime[`${oid}_Zcheck`]
          this.reload()
        })
      }).catch(() => {
      })
    },
    subz(s, id) {
      this.toSubInfo = id
      if (s === 1) {
        zCheck(this.template.tid, this.toSubInfo).then(res => {
          this.signModelValue[res.data.oid].zcheck = res.data.zcheck
          this.getCheckTime(this.template.tid)
          this.reload()
          this.$message.success('签字成功')
        })
      } else {
        const formData = new FormData()
        formData.append('file', s)
        zCheck(this.template.tid, this.toSubInfo, formData).then(res => {
          this.signModelValue[res.data.oid].zcheck = res.data.zcheck
          this.getCheckTime(this.template.tid)
          this.reload()
          this.$message.success('签字成功')
        })
      }
    },
    handleDownload(fileName, path) {
      const url = BASE_URL + path
      const el = document.createElement('a')
      el.style.display = 'none'
      el.setAttribute('target', '_blank')
      /**
       * download的属性是HTML5新增的属性
       * href属性的地址必须是非跨域的地址，如果引用的是第三方的网站或者说是前后端分离的项目(调用后台的接口)，这时download就会不起作用。
       * 此时，如果是下载浏览器无法解析的文件，例如.exe,.xlsx..那么浏览器会自动下载，但是如果使用浏览器可以解析的文件，比如.txt,.png,.pdf....浏览器就会采取预览模式
       * 所以，对于.txt,.png,.pdf等的预览功能我们就可以直接不设置download属性(前提是后端响应头的Content-Type: application/octet-stream，如果为application/pdf浏览器则会判断文件为 pdf ，自动执行预览的策略)
       */
      fileName && el.setAttribute('download', fileName)
      el.href = url
      console.log(el)
      document.body.appendChild(el)
      el.click()
      document.body.removeChild(el)
    },
    handleDelete(fid) {
      this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFile(fid).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          getFile(this.template.tid).then(res => {
            this.fileData = res.data
          })
        })
      })
    },
    upFile(ref) {
      this.getFileDom(ref).click()
    },
    getFileDom(oid) {
      if (oid) {
        return this.$refs[`singleFile${oid}`][0]
      } else {
        return this.$refs.singleFile
      }
    },
    handleFileUpload(event, oid) {
      event.preventDefault()
      const formData = new FormData()
      let file = event.target.files[0]
      console.log(file)
      if (oid) {
        let fileName = file.name  // 保存文件名
        let fileName2 = fileName.split('.')  // 对文件名进行切割
        file = new File([file], `${oid}_${fileName2[0]}` + '.' + fileName2[1], {type: file.type})
      }
      formData.append('file', file)
      this.onUpload(formData)
    },
    onUpload(formData) {
      uploadOrderFile(formData, this.template.tid).then((res) => {
        this.$message.success('上传成功')
        getFile(this.template.tid).then(res => {
          this.fileData = res.data
        })
      }).catch((e) => {
        this.$message.error('上传失败')
      })
    },
    handleTo(uid) {
      this.saveAllContent().then(values => {
        moveOrder(this.template.tid, uid).then(async res => {
          this.$message.success('流转表单成功')
          this.$router.go(-1)
        })
        this.$message.error('保存失败，请重新保存')
      })
    },
    searchUser(page) {
      this.listLoading = true
      findUser(5, page, {name: this.queryUser.keyword}).then(response => {
        this.searchList = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleChange(file, fileList) {
      this.fileList = fileList
      const isLt5M = file.size / 1024 / 1024 > 20
      if (isLt5M) {
        this.$message.error(this.$t('images_size'), 'error')
        const currIdx = this.fileList.indexOf(file)
        this.fileList.splice(currIdx, 1)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}

.check-block {
  font-weight: bold;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  color: rgb(96, 98, 102);
}

.space-item {
  width: 100%;

  ::v-deep.el-form-item__content {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
}
</style>
<style>
.fl {
  z-index: 500 !important;
}
</style>
